package com.dragon.utilslibrary.tools;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;



public class AESCBC {

    private static AESCBC instance = null;

    private AESCBC() {

    }

    public static AESCBC getInstance() {
        if (instance == null)
            instance = new AESCBC();
        return instance;
    }

    /**
     * 加密
     * @param sSrc 明文
     * @param sKey 密钥
     * @param ivParameter 向量已
     * @return byte[] 密文
     */
    public byte[] encrypt(byte[] sSrc, byte[] sKey, byte[] ivParameter) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter);//使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(sSrc);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解密
     * @param sSrc 密文
     * @param sKey 密钥
     * @param ivParameter 向量IV
     * @return 明文byte[]
     */
    public byte[] decrypt(byte[] sSrc, byte[] sKey, byte[] ivParameter) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(sSrc);
        } catch (Exception ex) {
            return null;
        }
    }

}
